package cmd

import (
	"dragonfly/common/config"
	"encoding/json"
	"fmt"
	"io/ioutil"

	"github.com/spf13/cobra"
	jww "github.com/spf13/jwalterweatherman"
)

var (
	genCmd = &cobra.Command{
		Use:   "gen",
		Short: "gen some files",
		Long:  "A collection of several useful generators.",
	}

	genConfigCmd = &cobra.Command{
		Use:   "config",
		Short: "generate config file",
		Long: `If config file is exist, this command will read and export Config struct to a file.
otherwise this command will set default config and generate a new file.
`,
		RunE: genConfigFunc,
	}

	genCompletionCmd = &cobra.Command{
		Use:   "autocomplete",
		Short: "generate shell autocompletion script",
		Long: `By default, the file is written directly to /etc/bash_completion.d for convenience,
and the command may need superuser rights.
`,
		RunE: genAutocompleteFunc,
	}
)

func init() {
	genConfigCmd.Flags().StringP("file", "f", "defaults.json", "Export config file")
	genCompletionCmd.Flags().StringP("completionfile", "", "/etc/bash_completion.d/dragonfly",
		"autocompletion file (default /etc/bash_completion.d/dragonfly")
	genCmd.AddCommand(
		genConfigCmd,
		genCompletionCmd,
	)
	RootCmd.AddCommand(genCmd)
}

func genConfigFunc(command *cobra.Command, args []string) error {
	filePath, err := command.Flags().GetString("file")
	if err != nil {
		return fmt.Errorf("No config file provided.")
	}

	cfg := &config.Config{}

	cfg.SetDefaults()

	b, err := json.MarshalIndent(cfg, "", "    ")
	if err != nil {
		return fmt.Errorf("Json config decode faild. %v", err)
	}

	err = ioutil.WriteFile(filePath, b, 0644)
	if err != nil {
		return fmt.Errorf("Dump config failed. %s", err)
	}

	return nil
}

func genAutocompleteFunc(command *cobra.Command, args []string) error {
	filePath, err := command.Flags().GetString("completionfile")
	if err != nil {
		return fmt.Errorf("No bash_completion script file provided.")
	}

	err = RootCmd.GenBashCompletionFile(filePath)
	if err != nil {
		return err
	}

	jww.FEEDBACK.Println("Bash completion file for Dragonfly saved to", filePath)
	return nil
}
